﻿#define _CRT_SECURE_NO_WARNINGS 1

#include"SLTNode.h"


//单链表的打印
void SLTPrint(SLT* phead)
{
	SLT* pcut = phead;
	while (pcut)
	{
		printf("%d->", pcut->date);
		pcut = pcut->next;
	}
	printf("NULL\n");
}

SLT* SLTBuyNode(SLTDataType x)
{
	SLT* newnode = (SLT*)malloc(sizeof(SLT));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->date = x;
	newnode->next = NULL;
	return newnode;

}
//单链表的尾插
void SLTPushBack(SLT** pphead, SLTDataType x)
{
	assert(pphead);
	SLT* newnode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLT* ptail = (*pphead);
		while (ptail->next)
		{
			ptail = ptail->next;
		}
		ptail->next = newnode;
	}
	
}

//单链表的头插
void SLTPushFront(SLT** pphead, SLTDataType x)
{
	assert(pphead);
	SLT* newnode =SLTBuyNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

//单链表的尾删
void SLTPopBack(SLT** pphead)
{
	assert(pphead);
	assert(*pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLT* pev = *pphead;
		SLT* ptail = *pphead;
		while (ptail->next)
		{
			pev = ptail;
			ptail = ptail->next;
		}
		free(ptail);
		ptail = NULL;
		pev->next = NULL;
	}
}


//单链表的头删
void SLTPopFront(SLT** pphead)
{
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLT* prcut = *pphead;
		*pphead = prcut->next;
		free(prcut);
		prcut = NULL;
	}
}

//查找
SLT* SLTFind(SLT* phead, SLTDataType x)
{
	assert(phead);
	SLT* prcut = phead;
	while (prcut)
	{
		if (prcut->date == x)
		return prcut;
		prcut = prcut->next;
	}
	return NULL;
}

//在指定位置之前插⼊数据
void SLTInsert(SLT** pphead, SLT* pos, SLTDataType x)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLT* newnode = SLTBuyNode(x);

	SLT* prev = *pphead;
	if (prev == pos)
	{
		newnode->next = prev;
		*pphead = newnode;
	}
	else
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		newnode->next = pos;
		prev->next = newnode;
	}
}

//在指定位置之后插⼊数据
void SLTInsertAfter(SLT* pos, SLTDataType x)
{
	assert(pos);
	SLT* newnode = SLTBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;

}

//删除pos节点
void SLTErase(SLT** pphead, SLT* pos)
{
	assert(pphead);
	assert(*pphead);
	assert(pos);

	if (pos == *pphead)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLT* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
	
}

//删除pos之后的节点
void SLTEraseAfter(SLT* pos)
{
	assert(pos);
	assert(pos->next);
	SLT* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}

//销毁链表
void SListDesTroy(SLT** pphead)
{
	assert(pphead);
	assert(*pphead);

	SLT* prcut = *pphead;
	while (prcut)
	{
		SLT* next = prcut->next;
		free(prcut);
		prcut = next;
	}
	*pphead = NULL;
}